#!/bin/bash

# Server-side verification and restart script
# Run this script directly on the production server (47.237.10.129)

echo "=== CumrBull Backend Service Verification & Restart ==="
echo "Run this script on the production server as root"
echo

# Check routes directory and files
echo "1. Checking routes directory..."
cd /opt/cumrbull/backend/src/routes/
ls -la
echo

# Count route files
echo "2. Counting route files..."
echo "Total .js files: $(ls -1 *.js 2>/dev/null | wc -l)"
echo "Expected files: auth.js users.js menu.js orders.js coupons.js payments.js admin.js"
echo

# Check file contents (first few lines)
echo "3. Checking file contents..."
for file in auth.js users.js menu.js orders.js coupons.js payments.js admin.js; do
    if [ -f "$file" ]; then
        echo "✓ $file exists ($(wc -l < $file) lines)"
        head -3 "$file" | grep -E "(express|router|module.exports)" && echo "  - Valid Express route structure"
    else
        echo "✗ $file missing"
    fi
done
echo

# Stop current backend service
echo "4. Stopping current backend service..."
pkill -f "node src/app.js" || echo "No running backend process found"
sleep 2

# Check if port 3000 is free
echo "5. Checking port 3000..."
if netstat -tlnp | grep :3000; then
    echo "Port 3000 still in use, killing processes..."
    fuser -k 3000/tcp
    sleep 2
else
    echo "Port 3000 is free"
fi

# Start backend service
echo "6. Starting backend service..."
cd /opt/cumrbull/backend/
nohup node src/app.js > backend.log 2>&1 &
BACKEND_PID=$!
echo "Backend started with PID: $BACKEND_PID"
sleep 3

# Verify service is running
echo "7. Verifying service status..."
if ps -p $BACKEND_PID > /dev/null; then
    echo "✓ Backend service is running (PID: $BACKEND_PID)"
else
    echo "✗ Backend service failed to start"
    echo "Last 10 lines of log:"
    tail -10 backend.log
    exit 1
fi

# Check port binding
echo "8. Checking port binding..."
if netstat -tlnp | grep :3000; then
    echo "✓ Backend is listening on port 3000"
else
    echo "✗ Backend is not listening on port 3000"
    echo "Service log:"
    tail -20 backend.log
    exit 1
fi

# Test API endpoint
echo "9. Testing API endpoint..."
if curl -s http://localhost:3000/api/health > /dev/null; then
    echo "✓ API endpoint responding"
else
    echo "⚠ API endpoint test failed (may be normal if /api/health doesn't exist)"
fi

echo
echo "=== Verification Complete ==="
echo "Backend service status: $(ps aux | grep 'node src/app.js' | grep -v grep | wc -l) process(es) running"
echo "Port 3000 status: $(netstat -tlnp | grep :3000 | wc -l) listener(s)"
echo
echo "To monitor logs: tail -f /opt/cumrbull/backend/backend.log"
echo "To stop service: pkill -f 'node src/app.js'"
echo "To restart service: cd /opt/cumrbull/backend && nohup node src/app.js > backend.log 2>&1 &"